package hn.cch.redisson.controller;

import hn.cch.redisson.constant.RedissonConstant;
import hn.cch.redisson.service.RedissonService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicInteger;

@RequestMapping(value = "/redisson")
@RestController
public class RedissonController {

    private static final Logger logger = LoggerFactory.getLogger(RedissonController.class);

    @Autowired
    private RedissonService redissonService;

    @GetMapping(value = "/useDistributedLock")
    public String useDistributedLock() {
        logger.info("useDistributedLock");
        // 处理自增key不存在问题
        if (!redissonService.isExists(RedissonConstant.keyName)) {
            redissonService.setInteger(RedissonConstant.keyName, 0);
        }
        AtomicInteger atomicInteger = new AtomicInteger();
        redissonService.useDistributedLock(RedissonConstant.lockKey, () -> {
            try {
                Thread.sleep(1000 * 10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            do {

                atomicInteger.getAndIncrement();
            } while (!redissonService.increment(RedissonConstant.keyName));
        });
        return String.format("%s:%d:%d", RedissonConstant.keyName,
            redissonService.getInteger(RedissonConstant.keyName), atomicInteger.get());
    }

}
